package com.da.alipay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.da.alipay.bean.AlipayBean;
import com.da.alipay.bean.AlipayCommon;
import com.da.alipay.service.PayService;
import com.da.alipay.util.PayClientUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author JokerDa.
 * @date 2021/1/27 10:52
 * Description:
 */
@Service
public class PayServiceImpl2 implements PayService {
    @Autowired
    private PayClientUtil2 payClientUtil2;
    @Autowired
    private AlipayCommon alipayCommon;

    @Override
    public String aliPay(AlipayBean alipayBean) throws AlipayApiException {
        // 1、获得初始化的AlipayClient
        String returnUrl = alipayCommon.getReturnUrl();
        String notifyUrl = alipayCommon.getNotifyUrl();
        AlipayClient alipayClient = payClientUtil2.getDefaultClient();
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(returnUrl);
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(notifyUrl);
        // 封装参数
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
        // 3、请求支付宝进行付款，并获取支付结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        // 返回付款信息
        return result;
    }

    @Override
    public String payQuery(String outTradeNo) throws AlipayApiException {
        AlipayClient alipayClient = payClientUtil2.getDefaultClient();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject object = new JSONObject();
        object.put("out_trade_no", outTradeNo);
        request.setBizContent(object.toJSONString());
        return alipayClient.execute(request).getBody();
    }
}
